package com.badu.app.service.impl;

import com.badu.app.domain.AppUser;
import com.badu.app.dao.AppUserMapper;
import com.badu.app.service.IAppUserService;
import com.badu.common.enums.ServerErrorEnum;
import com.badu.common.utils.StringUtils;
import com.badu.fx.service.IFxLevelRecordService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 移动端的用户表 服务实现类
 * </p>
 *
 * @author astupidcoder123
 * @since 2021-01-14
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

	@Autowired
	private AppUserMapper appUserMapper;
	@Autowired
	private IFxLevelRecordService fxLevelRecordService;
	
	@Override
	public AppUser getAppUserByOpenId(String openId) {
		List<AppUser> selectList = appUserMapper.selectList(new EntityWrapper<AppUser>()
				.eq("openId", openId));
		if(CollectionUtils.isEmpty(selectList))
			Assert.state(false, ServerErrorEnum.USER_NONENTITY.getValue());
			
		return selectList.get(0);
	}

	@Override
	public int updateAppUser(AppUser appUser) {
		if(StringUtils.isNotBlank(appUser.getOpenId()))
			return appUserMapper.update(appUser, new EntityWrapper<AppUser>().eq("openId", appUser.getOpenId()));
		
		return appUserMapper.updateById(appUser);
	}

	@Override
	public int deleteAppUser(AppUser appUser) {
		if(StringUtils.isNotBlank(appUser.getOpenId()))
			return appUserMapper.delete(new EntityWrapper<AppUser>().eq("openId", appUser.getOpenId()));
		
		return appUserMapper.deleteById(appUser.getId());
	}

	@Override
	public int addAppUser(AppUser appUser) {
		//生成用户的邀请码
		appUser.setRegisterCode(StringUtils.generateRegisterCodeSn());
		return appUserMapper.insert(appUser);
	}

	@Override
	public int appUserSttingRegisterCode(String openId, String resisterCode) {
		//先查询邀请码是否有效
		List<AppUser> registerCodeList = appUserMapper.selectList(new EntityWrapper<AppUser>().eq("registerCode'", resisterCode));
		if(CollectionUtils.isEmpty(registerCodeList))
			Assert.state(false, ServerErrorEnum.INVALID_REGISTER_CODE.getValue());
		
		//设置邀请记录保存用户级别关联
		return fxLevelRecordService.addFxLevelRecord(registerCodeList.get(0).getOpenId(), openId);
	}

}
